package com.xiaochong.bitong.job.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.bitong.job.component.RedisCacheComponent;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.mapper.ExchangeInfoMapper;
import com.xiaochong.tir.common.data.mapper.ExchangeTransactionpairMiddleMapper;
import com.xiaochong.tir.common.data.mapperSearchResult.ExchangeTransactionpair;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.po.ExchangeInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.vo.ApiCapitalInflowSituationVo;
import com.xiaochong.tir.common.data.vo.CurrencyQuotationResultVo;
import com.xiaochong.tir.common.util.RedisKeyApp;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Description: java类作用描述
 * @Author: org
 * @CreateDate: 2018/8/14 16:51
 */
@Service
public class CoinAndPairSearchService {


    @Autowired
    private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;
    @Autowired
    private RedisServer redisConfig;
    @Autowired
    private RedisCacheComponent redisCacheComponent;

    /**
     * 交易对排名根据成交额
     */
    public void calculatePairSort() {
        try {
            //查询所有交易所-交易对
            ExchangeTransactionpairMiddle query = new ExchangeTransactionpairMiddle();
            List<ExchangeTransactionpair> middleList = exchangeTransactionpairMiddleMapper.selectByEntityListOfKLine(query);
            String redisKey;
            String data;
            ApiCapitalInflowSituationVo today ;
            //循环放入成交额
            for(ExchangeTransactionpair pair : middleList){
                //获取24小时净流入,24h成交额
                JSONObject jsonObject;
                redisKey = RedisKeysUtils.API_SERVICE_TRADES_24H_CAPITAL_FLOW_DATA+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
                data = redisConfig.get(redisKey);
                BigDecimal buyM = BigDecimal.ZERO;
                BigDecimal sellM = BigDecimal.ZERO;
                if(StringUtils.isNotBlank(data)){
                    jsonObject = JSON.parseObject(data);
                    today = JSON.parseObject(JSON.toJSONString(jsonObject.get("dayHours")),ApiCapitalInflowSituationVo.class);
                    if(today != null && StringUtils.isNotBlank(today.getBuyAmount()) && StringUtils.isNotBlank(today.getSellAmount())){
                        buyM = new BigDecimal(today.getBuyAmount());
                        sellM = new BigDecimal(today.getSellAmount());
                        buyM = buyM.add(sellM);
                        buyM = getConverCut(buyM.toString());
                        pair.setAmount(buyM!=null?buyM:BigDecimal.ZERO);
                    }else{
                        pair.setAmount(BigDecimal.ZERO);
                    }
                }else{
                    pair.setAmount(BigDecimal.ZERO);
                }
            }
            //根据成交额排序，放入缓存中,降序排列
            Collections.sort(middleList, new Comparator<ExchangeTransactionpair>() {
                @Override
                public int compare(ExchangeTransactionpair o1, ExchangeTransactionpair o2) {
                    if(o1.getAmount().compareTo(o2.getAmount()) > 0){
                        return -1;
                    }else if(o1.getAmount().compareTo(o2.getAmount()) == 0){
                        return 0;
                    }else{
                        return 1;
                    }
                }
            });
            redisConfig.set(RedisKeyApp.SEARCH_PAIR,middleList);

        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("thread-交易对搜索定时存入redis数据error",e);
        }

    }
    public static BigDecimal getConverCut(String lastPriceB) {
        BigDecimal result = new BigDecimal(0);
        result = StringUtils.isNotBlank(lastPriceB)?new BigDecimal(lastPriceB).setScale(10,BigDecimal.ROUND_DOWN):result;
        if(result.compareTo(BigDecimal.valueOf(1)) >=0){
            result = result.setScale(2,BigDecimal.ROUND_DOWN);
        }else{
            BigDecimal divisor = BigDecimal.ONE;
            MathContext mc = new MathContext(5);
            result = result.divide(divisor, mc);
        }
        return result;
    }

    /**
     * 货币按照市值排序，降序
     */
    public void calculateCoinSort() {
        try {
            List<CurrencyInfo> CurrencyInfoList= redisCacheComponent.getCurrencyList();
            if(CurrencyInfoList != null && CurrencyInfoList.size() > 0){
                for(CurrencyInfo currencyInfo : CurrencyInfoList){
                    currencyInfo.setCurrencyIndustryList(null);
                    currencyInfo.setCurrencyConceptList(null);
                    currencyInfo.setSelfSelectFlag(2);
                    currencyInfo.setMarketCapCny(pullMardetPrice(currencyInfo.getCmcId()));
                }
                //排序,按照市值
                Collections.sort(CurrencyInfoList, new Comparator<CurrencyInfo>() {
                    @Override
                    public int compare(CurrencyInfo o1, CurrencyInfo o2) {
                        if(o1.getMarketCapCny().doubleValue() > o2.getMarketCapCny().doubleValue()){
                            return -1;
                        }else if(o1.getMarketCapCny().doubleValue() == o2.getMarketCapCny().doubleValue()){
                            return 0;
                        }else{
                            return 1;
                        }
                    }
                });
                redisConfig.set(RedisKeyApp.SEARCH_COIN,CurrencyInfoList);
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("thread-货币搜索定时存入redis数据error",e);
        }
    }
    /**
     * 拉取市值，排名使用
     * @param cmcId
     * @return
     */
    public Double pullMardetPrice(String cmcId){
        String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+cmcId;
        String result=redisConfig.get( redisCacheKey);
        if (result!=null){
            LogTrace.info("getCurrencyByCmcId" , "resultKeyRedis" , redisCacheKey );
            CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
            if(currencyQuotationResultVo!=null && currencyQuotationResultVo.getMarketCapCny()!=null){
                return currencyQuotationResultVo.getMarketCapCny();
            }
        }
        return 0D;
    }
}
        /*ExchangeInfo exchangeInfo=new ExchangeInfo();
        exchangeInfo.setEnableFlag( true );
        exchangeInfo.setDeleteFlag( false );
        exchangeInfo.setKlineStatus( true );
        List<ExchangeInfo> infoList=exchangeInfoMapper.selectByEntityList( exchangeInfo );
        for(ExchangeInfo exchange : infoList){
            ExchangeTransactionpairMiddle exchangeTransactionpairMiddle=new ExchangeTransactionpairMiddle();
            exchangeTransactionpairMiddle.setEnableFlag( true );
            exchangeTransactionpairMiddle.setExchangeId( exchange.getId() );
            List<ExchangeTransactionpairMiddle> exchangeMiddleList = exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );
        }*/
